/**
 * 
 */
package org.gnf.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.gnf.genewiki.Config;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * @author bgood
 *
 */
public class MyGeneInfo {

	/**
	 * @param args
	 * @throws UnsupportedEncodingException 
	 */
	public static void main(String[] args) throws UnsupportedEncodingException {
	//	String t = "CDK2";
	//	Set<String> s = mapGeneSymbol2NCBIGene(t);
		
//		String t = "C0H8T3";//"Q0GN75";
//		Set<String> s = mapUniprot2NCBIGene(t).keySet();
//		if(s==null||s.size()==0){
//			s = mapGeneAlias2NCBIGene(t);
//		}
//		System.out.println(s);
		System.out.println(getSymbolByGeneid("1082"));
	}

	
	public static String getSymbolByGeneid(String id) throws UnsupportedEncodingException{
		String symbol = "";
		String jsonr = getGeneInfoPublic(id);
		if(jsonr==null||jsonr.length()==0){
			return null;
		}
		//System.out.println(jsonr);
		try {
			JSONObject r = new JSONObject(jsonr);
			if(r==null){
				return null;
			}
			symbol = r.getString("symbol");
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return symbol;
	}
	
	public static Map<String, String> mapUniprot2NCBIGene(String id) throws UnsupportedEncodingException{
		Map<String, String> mapped = new HashMap<String, String>();
		String jsonr = queryHumanGeneLocalDev(id, "uniprot");
		//System.out.println(jsonr);
		try {
			JSONObject r = new JSONObject(jsonr);
			if(r==null){
				return null;
			}
			JSONArray rows = (JSONArray) r.get("rows");
			if(rows== null){
				return null;
			}
			for(int i=0; i<rows.length(); i++){
				JSONObject job = (JSONObject) rows.get(i);
				String gene = job.getString("id");

				JSONObject f = (JSONObject)job.get("fields");
				JSONObject fields = (JSONObject)f.get("value");
				String symbol = fields.getString("symbol");
				String name = fields.getString("name");
				int taxid = fields.getInt("taxid");
				
				mapped.put(gene, symbol+"\t"+name+"\t"+taxid);
				
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return mapped;
	}
	
	public static Set<String> mapGeneSymbol2NCBIGene(String id) throws UnsupportedEncodingException{
		Set<String> mapped = new HashSet<String>();
		String jsonr = queryHumanGeneLocalDev(id, "symbol");
		//System.out.println(jsonr);
		try {
			JSONObject r = new JSONObject(jsonr);
			if(r==null){
				return null;
			}
			JSONArray rows = (JSONArray) r.get("rows");
			if(rows== null){
				return null;
			}
			for(int i=0; i<rows.length(); i++){
				JSONObject job = (JSONObject) rows.get(i);
				mapped.add(job.getString("id"));
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return mapped;
	}

	public static String queryHumanGeneLocalDev(String geneid, String idtype) throws UnsupportedEncodingException{
		String out = "";
		//http://mygene.info/query?q=cdk2+AND+species:human
		String encoded = URLEncoder.encode(geneid, "UTF8");
		GetMethod get = new GetMethod("http://cwu-stage/query?q="+idtype+":"+encoded+"+AND+species:human");
		// Get HTTP client
		HttpClient httpclient = new HttpClient();
		// Execute request
		try {
			int result = httpclient.executeMethod(get);
			// Display status code
		//	System.out.println("Response status code: " + result);
			// Display response
		//	System.out.println("Response body: ");
		//	out = get.getResponseBodyAsString();
		//	System.out.println(out);
		    InputStream s = get.getResponseBodyAsStream(); 
		    out = HttpUtil.convertStreamToString(s);
		
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			// Release current connection to the connection pool once you are done
			get.releaseConnection();
		}
		return out;
	}

	public static String getGeneInfoPublic(String geneid) throws UnsupportedEncodingException{
		if(geneid==null){
			return null;
		}
		String out = "";
		//http://mygene.info/query?q=cdk2+AND+species:human
		String encoded = URLEncoder.encode(geneid, "UTF8");
		//http://mygene.info/gene/117
		GetMethod get = new GetMethod("http://mygene.info/gene/"+encoded);
		// Get HTTP client
		HttpClient httpclient = new HttpClient();
		// Execute request
		try {
			int result = httpclient.executeMethod(get);
			// Display status code
		//	System.out.println("Response status code: " + result);
			// Display response
		//	System.out.println("Response body: ");
			out = get.getResponseBodyAsString();
		//	System.out.println(out);
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			// Release current connection to the connection pool once you are done
			get.releaseConnection();
		}
		return out;
	}
	
	public static String queryHumanGenePublic(String geneid, String idtype) throws UnsupportedEncodingException{
		String out = "";
		//http://mygene.info/query?q=cdk2+AND+species:human
		String encoded = URLEncoder.encode(geneid, "UTF8");
		GetMethod get = new GetMethod("http://mygene.info/query?q="+idtype+":"+encoded+"+AND+species:human");
		// Get HTTP client
		HttpClient httpclient = new HttpClient();
		// Execute request
		try {
			int result = httpclient.executeMethod(get);
			// Display status code
		//	System.out.println("Response status code: " + result);
			// Display response
		//	System.out.println("Response body: ");
			out = get.getResponseBodyAsString();
		//	System.out.println(out);
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			// Release current connection to the connection pool once you are done
			get.releaseConnection();
		}
		return out;
	}
	
	public static String queryHumanGene(String geneid) throws UnsupportedEncodingException{
		String out = "";
		//http://mygene.info/query?q=cdk2+AND+species:human
		String encoded = URLEncoder.encode(geneid, "UTF8");
		GetMethod get = new GetMethod("http://mygene.info/query?q="+encoded+"+AND+species:human");
//		NameValuePair[] data = {
//				new NameValuePair("q", geneid+"+AND+species:human"),
//		};
		// Request content will be retrieved directly
		// from the input stream
		//post.setRequestBody(data);
		// Get HTTP client
		HttpClient httpclient = new HttpClient();
		// Execute request
		try {
			int result = httpclient.executeMethod(get);
			// Display status code
		//	System.out.println("Response status code: " + result);
			// Display response
		//	System.out.println("Response body: ");
			out = get.getResponseBodyAsString();
		//	System.out.println(out);
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			// Release current connection to the connection pool once you are done
			get.releaseConnection();
		}
		return out;
	}
	
	public static Set<String> mapGeneAlias2NCBIGene(String id) throws UnsupportedEncodingException{
		Set<String> mapped = new HashSet<String>();
		String jsonr = queryHumanGeneLocalDev(id, "alias");
		//System.out.println(jsonr);
		try {
			JSONObject r = new JSONObject(jsonr);
			if(r==null){
				return null;
			}
			JSONArray rows = (JSONArray) r.get("rows");
			if(rows== null){
				return null;
			}
			for(int i=0; i<rows.length(); i++){
				JSONObject job = (JSONObject) rows.get(i);
				mapped.add(job.getString("id"));
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return mapped;
	}
}
